package org.heima.utils;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Iterator;

public class XmlParseUtils {
    public void parse(InputStream inputStream){
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);
            String xpath = "/configuration/environments";
            Element environments = (Element)document.selectSingleNode(xpath);
            Attribute aDefault = environments.attribute("default");
            System.out.println(aDefault.getValue());
            String xpath2 = "/configuration/environments/environment[@id='"+ aDefault.getValue() +"']";
            Element environment = (Element)document.selectSingleNode(xpath2);//获取environment属性
            Element transactionManager = environment.element("transactionManager");
            String transactionManagerType = transactionManager.attributeValue("type");
            System.out.println(transactionManagerType);
            Element dataSource = environment.element("dataSource");
            String dataSourceType = dataSource.attributeValue("type");
            System.out.println(dataSourceType);
            Iterator<Element> elementIterator = dataSource.elementIterator();
            while (elementIterator.hasNext()) {
                Element element = elementIterator.next();
                Attribute name = element.attribute("name");
                Attribute value = element.attribute("value");
                System.out.println(name.getValue() + "=" + value.getValue());
            }

        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }
}
